<?php

namespace App\Http\Middleware;

use App\Models\Apipro;
use App\Models\CardType;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ApiConfigMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response|RedirectResponse) $next
     * @return JsonResponse
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            $url = $request->url();
            if (stripos($url, "/api/") === false) {
                return response()->json(['code' => 400, 'msg' => '该接口不存在']);
            }

            $config = Apipro::all();
            $tags = $this->categorizeTagsByCheckQuery($config);
            $partAfterApi = substr($url, strpos($url, "/api/") + strlen("/api/"));
            if (in_array($partAfterApi, $tags['no_check_query'], true)) {
                $apili = Apipro::where('tag', $partAfterApi)->first();
                if (!$apili || !$apili->status || $apili->is_vip) {
                    $rest= $this->handleApiValidationError($apili, '该接口不存在', '接口已经关闭', '该接口需要vip');
                    if($rest){
                        return $rest;
                    }else{
                        return $next($request);
                    }
                }
            }elseif (in_array($partAfterApi, $tags['check_query'], true)) {
                if (!$request->has('type')) {
                    return response()->json(['code' => 400, 'msg' => '缺少参数']);
                }
                $type = $request->input('type', '');
                $apili = Apipro::where('tag', $partAfterApi)
                    ->whereJsonContains('querys', ['value' => $type])
                    ->first();
                if (!$apili || !$apili->status || $apili->is_vip) {
                    $rest= $this->handleApiValidationError($apili, '该接口不存在', '接口已经关闭', '该接口需要vip');
                    if($rest){
                        return $rest;
                    }else{
                        return $next($request);
                    }
                }
            }else {
                return response()->json(['code' => 400, 'msg' => '该接口不存在']);
            }
            return $next($request);
        } catch (\Exception $e) {
            return response()->json(['code' => 500, 'msg' => '服务器错误'], 500);
        }
    }

    private function categorizeTagsByCheckQuery($config): array
    {
        $tags = ['check_query' => [], 'no_check_query' => []];
        foreach ($config as $item) {
            $tags[$item->is_check_query ? 'check_query' : 'no_check_query'][] = $item->tag;
        }
        return $tags;
    }

    private function handleApiValidationError($apili, string $notExistsMsg, string $closedMsg, string $vipMsg)
    {
        if (!$apili) {
            return response()->json(['code' => 400, 'msg' => $notExistsMsg]);
        }
        if (!$apili->status) {
            return response()->json(['code' => 400, 'msg' => $closedMsg]);
        }
        if ($apili->is_vip) {
            if (!auth('api')->check()) {
                return response()->json(['code' => 401, 'msg' => '请先登录']);
            } else {
                $user = auth('api')->user()->load('userCard');
                if (!$user->userCard) {
                    return response()->json(['code' => 433, 'msg' => $vipMsg]);
                } else {
                    $card_effective_time = CardType::query()->where('id', $user->userCard->card_id)->value('effective_time');
                    $vipDurationInSeconds = $card_effective_time * 24 * 60 * 60;
                    $vipEndTime = $user->userCard->created_at->addSeconds($vipDurationInSeconds);
                    if ($vipEndTime->isPast()) {
                        return response()->json(['code' => 433, 'msg' => $vipMsg]);
                    }
                }
            }
        }
    }


}
